import { guid, is2DArray, mergeObjects, isEqual } from "../core/utils";
import { ParamManager } from "../gpu/ParamManager";
import { Action } from "./Action";
import { Emitter } from "./Emitter";
import { EmitterComputer } from "./EmitterComputer";
import { particleParam } from "./ParticleType";
import { PositionShape, VelocityShape } from "./shape";
import { Engine } from '../Engine';


/**
 * 粒子系统
 * @class
 * @memberof w.Particle
 */
export class Particle {
    get position() {
        return this.params.position;
    }

    set position(value) {
        if (!isEqual(this.params.position, value)) {
            this.params.position = value;
            this.destroy()
            this.emitter = new EmitterComputer(this.params)
            !this.timeid && this.update()
        }
    }
    constructor(options) {
        this.renderSystem = Engine.instance._register._systemManager._systems.get("rendersystem")
        this.createEmitter(options)
    }
    //  创造粒子发射器
    async createEmitter(options) {
        if (!options) {
            throw new Error('无构造粒子项')
        }
        this.emitterOptions = { ...options }
        if (!this.emitterOptions.id) {
            this.emitterOptions.id = guid()
        }
        const tempEmitterOptions = mergeObjects(particleParam, this.emitterOptions)
        this.params = tempEmitterOptions
        this.emitter = new EmitterComputer(tempEmitterOptions)
        // this.emitter = new Emitter(tempEmitterOptions)
        !this.timeid && this.update()
    }

    // 显示隐藏
    get visible() {
        return this._visible
    }
    set visible(v) {
        this._visible = v
        if (this._visible !== v) {
            this.emitter._object3D.visibility = v;
        }
    }
    /*
    更新
    */
    update() {
        this.timeid = setInterval(() => {
            this.emitter.update(0.016)
        }, 17);
    }
    //   销毁
    destroy() {
        clearInterval(this.timeid)
        this.timeid = null
        this.emitter._object3D.destroy()
        for (let index = 0; index < this.renderSystem.computers.length; index++) {
            const element = this.renderSystem.computers[index];
            if (this.emitter.id === element.id) {
                this.renderSystem.computers.splice(index, 1)
            }
        }
        this.emitter._particlesBuffer && this.emitter._particlesBuffer.destroy()
    }
}